//tactile.logger.setConfig({
// 	level: tactile.logger.level.info
//});

var page = tactile.page;
var scroller;
var fitroomTopScroller;
var fitroomBotScroller;

var fashiongridloader = {
	gridloader	: new Array(3),
	gridloaded	: new Array(false, false, false),
	initloader : function() {
		BasketDB.init();
		BasketDB.do('checkQtyHandler');
		
        for (var index=0;index<3;index++) {
               (function(index) {
					fashiongridloader.gridloader[index] = new tactile.ContentLoader();
					fashiongridloader.gridloader[index].onsuccess.subscribe( function(e) { fashiongridloader.addGrid(index,  e); });
					fashiongridloader.gridloader[index].onerror.subscribe( function(e) { fashiongridloader.addGridException(e); });  
               })(index);
               fashiongridloader.loadFashionGrid(index);             
        }				
	},
	loadFashionGrid : function(index) {
		if (!fashiongridloader.gridloaded[index]) {
			fashiongridloader.gridloader[index].load({
				url : "/ipad/remote/fashiongrid/fashiongrid" + (index+1) + ".xml"
			})
		}
	},
	addGrid : function(index,  e) {
		
		var pagename = "fashiongrid" + (index+1) + ".xml";
		var objname  = "vw-fashionspreadgrid" + (index+1);
		
		var currview = tactile.View.cast(page.getComponent(objname));
		if (currview != 'undefined' && currview != null) {
			var vwfashiongridtitle = tactile.View.cast(fashiongridloader.gridloader[index].getComponent("vw-fashiongrid" + (index+1) + "-title"));
			if (vwfashiongridtitle != 'undefined' && vwfashiongridtitle != null) {
				currview.append(vwfashiongridtitle);
			}
			
			var vwfashiongriditemlist = tactile.View.cast(fashiongridloader.gridloader[index].getComponent("vw-fashiongrid" + (index+1) + "-itemlist"));
			if (vwfashiongriditemlist != 'undefined' && vwfashiongriditemlist != null) {
				currview.append(vwfashiongriditemlist);
			}			
		}			
		
		if (e.url.indexOf(pagename) != -1) {
			fashiongridloader.gridloaded[index] = true;
		}	
		
		fashiongrid.initGrid(index);	
		
		
//		if (fashiongridloader.gridloaded[0]==true &&
//				fashiongridloader.gridloaded[1]==true &&
//				fashiongridloader.gridloaded[2]==true) {
//			var timeoutHandler = window.setTimeout(function () {
//				loadingmask.hide();
//			}, 1000);		
//		};		
	},
	addGridException : function(e) {
		console.log("Error loading the content: " + e.url + ", message: " + e.status + " " + e.message);
	}
}

var customloader = {

	fittingroomloaded : false,
	fittingroomloader : undefined,
	shoppingbasketloaded : false,
	shoppingbasketloader : undefined,

	initloader : function() {

		customloader.fittingroomloader = new tactile.ContentLoader();
		customloader.fittingroomloader.onsuccess.subscribe(customloader.addFittingRoomPage);
		customloader.fittingroomloader.onerror.subscribe(customloader.handleLoaderError);

		customloader.shoppingbasketloader = new tactile.ContentLoader();
		customloader.shoppingbasketloader.onsuccess.subscribe(customloader.addShoppingBasketPage);
		customloader.shoppingbasketloader.onerror.subscribe(customloader.handleLoaderError);

	},
	addFittingRoomPage : function(e) {
		var vwfittingroom = tactile.View.cast(customloader.fittingroomloader.getComponent("vw-content-fittingroom"));
		if (vwfittingroom != 'undefined' && vwfittingroom != null) {
			var content = page.getComponent("content");
			content.append(vwfittingroom);

			if (e.url.indexOf("fittingroom.xml") != -1) {
				customloader.fittingroomloaded = true;
			}
			
			// Add Dynamic Elements to Screen
			console.log('fitting room');
			
			// Adding Horizontal Scrolling
			var i = $('.item', '#myTopScroll .scroller').length;
			var j = parseFloat($('.item', '#myTopScroll .scroller').css('width')) + parseFloat($('.item', '#myTopScroll .scroller').css('margin-right'));
			var k = parseFloat($('#myTopScroll').css('padding-left'));
			$('#myTopScroll .scroller').css('width', (i*j)+k);
			fitroomTopScroller = new iScroll('myTopScroll', {hScrollbar:false, vScrollbar:false});
			
			var o = $('.item', '#myBotScroll .scroller').length;
			var p = parseFloat($('.item', '#myBotScroll .scroller').css('width')) + parseFloat($('.item', '#myBotScroll .scroller').css('margin-right'));
			var q = parseFloat($('#myBotScroll').css('padding-left'));
			$('#myBotScroll .scroller').css('width', (o*p) + q);
			fitroomBotScroller = new iScroll('myBotScroll', {hScrollbar:false, vScrollbar:false});

			// Edit Button
	       	$('#editme').click(function(e) {	       		
	       		_editme(e);	
	       	});	
		}
	},
	addShoppingBasketPage : function(e) {
		var vwshoppingbasket = tactile.View.cast(customloader.shoppingbasketloader.getComponent("vw-content-shoppingbasket"));
		if (vwshoppingbasket != 'undefined' && vwshoppingbasket != null) {
			var content = page.getComponent("content");
			content.append(vwshoppingbasket);

			if (e.url.indexOf("shoppingbasket.xml") != -1) {
				customloader.shoppingbasketloaded = true;
			}
			
			
			if($('#vw-content-shoppingbasket').length > 0) {
				if($('.item', '#basket_items').length == 0) {
					scroller = new iScroll('basket_items', {hScrollbar:false, vScrollbar:false});
					BasketDB.init();
					scroller.refresh();
				}
			}
		}
	},
	handleLoaderError : function(e) {
		console.log("Error loading the content: " + e.url + ", message: " + e.status + " " + e.message);
	}
}

var custom = {
	gridopen: false,
	supportedDevice : true,

	init : function() {

		console.log("Initialize");
		console.log("Detecting Device Type");
		if (tactile.Device.isDesktopBrowser) {
			console.log("Device is Desktop Browser");
		} else {
			if (tactile.Device.isTablet) {
				console.log("Device is a Tablet")
			} else {
				console.log("Device is not a tablet");
				if (tactile.Device.isSmartphone) {
					console.log("Device is not a smartphone");
					if (tactile.Device.isTouch) {
						console.log("Device is Touch Enabled");
					} else {
						console.log("Unsupported Device");
						supportedDevice = false;
					}
				} else {
					supportedDevice = false;
					console.log("Unsupported Device");
				}
			}
		}

		if (!custom.supportedDevice) {
			alert("Unsupported Device");
			return;
		}

		console.log("Attaching EventManager");
		
		// menu action
		tactile.EventManager.addListener("menu-fashionspread", "tap", function() {
			custom.viewFashionSpread();
			tactile.foundation.HistoryManager.addHistoryState({
				name: this.id,
				callback: 'function() {custom.backToFashionSpread();}'
			});
		} );
		tactile.EventManager.addListener("menu-fittingroom", "tap", function() {
			custom.viewFittingRoom();
			tactile.foundation.HistoryManager.addHistoryState({
				name: this.id,
				callback: 'function() {custom.viewFittingRoom();}'
			});
		});
		tactile.EventManager.addListener("menu-shoppingbasket", "tap", function() {
			custom.viewShoppingBasket();
			tactile.foundation.HistoryManager.addHistoryState({
				name: this.id,
				callback: 'function() {custom.viewShoppingBasket();}'
			});
		});

		// fashion spread action
		tactile.EventManager.addListener("mv-fashionspread", "swipe", function(e) {
			custom.slideFashionSpreadView(e);
			tactile.foundation.HistoryManager.addHistoryState({
				name: this.id,
				callback: 'function(e) {custom.backToFashionSpread();}'
			});
		});
		tactile.EventManager.addListener("mv-fashionspreadgrid", "swipe", function(e) {
			custom.slideFashionSpreadGridView(e);
			tactile.foundation.HistoryManager.addHistoryState({
				name: this.id,
				callback: 'function(e) {custom.backToFashionSpread();}'
			});
		});
		tactile.EventManager.addListener("btn-close-fashionspreadgrid", "tap", function(e) {
			custom.closeFashionGrid(e);
			tactile.foundation.HistoryManager.addHistoryState({
				name: this.id,
				callback: 'function(e) {custom.backToFashionSpread();}'
			});
		});
		tactile.EventManager.addListener("btn-show-fashionspreadgrid", "tap", function(e) {
			custom.openFashionGrid(e);
			tactile.foundation.HistoryManager.addHistoryState({
				name: this.id,
				callback: 'function(e) {custom.backToFashionSpread();}'
			});
		});
		
		
		// LIKE BUTTON
		$('#btn-show-fittingroom').click(function(e) {
			$(this).toggleClass('selected');
		});
	
		tactile.foundation.HistoryManager.addHistoryState({
			name: "menu-fashionspread",
			callback: 'function() {custom.viewFashionSpread();}'
		});	
		
		//loader
		customloader.initloader();
		fashiongridloader.initloader();
		fashiongrid.initloader();		
		
//		tactile.EventManager.addResizeListener(custom.detectOrientation);
//		
//		var rootcontainer = page.getComponent("root");
//		rootcontainer.onresize.subscribe(custom.detectOrientation);		
//		custom.detectOrientation();
	},
	detectOrientation: function(e) {
//		console.log("Size/Orientation Change");
//		
//		var msg = "";
//		msg += "heigth = " + e.height + ", ";
//		msg += "width = " + e.width + ", ";
//		msg += "top = " + e.top + ", ";
//		msg += "left = " + e.left;
//		console.log(msg);		
		
		custom.changeFashionSpreadImage(e);
	},
	changeFashionSpreadImage: function(e) {

		var fashionspread1 = page.getComponent("vw-fashionspread1");
		var fashionspread2 = page.getComponent("vw-fashionspread2");
		var fashionspread3 = page.getComponent("vw-fashionspread3");
		
		if(tactile.Device.screen.isLandscape()){

			fashionspread1.addClass("fashionspread1-landscape-bg");
			fashionspread1.removeClass("fashionspread1-portrait-bg");
			
			fashionspread2.addClass("fashionspread2-landscape-bg");
			fashionspread2.removeClass("fashionspread2-portrait-bg");
			
			fashionspread3.addClass("fashionspread3-landscape-bg");
			fashionspread3.removeClass("fashionspread3-portrait-bg");
			
			
		}else{

			fashionspread1.addClass("fashionspread1-portrait-bg");
			fashionspread1.removeClass("fashionspread1-landscape-bg");
			
			fashionspread2.addClass("fashionspread2-portrait-bg");
			fashionspread2.removeClass("fashionspread2-landscape-bg");
			
			fashionspread3.addClass("fashionspread3-portrait-bg");
			fashionspread3.removeClass("fashionspread3-landscape-bg");

		}		
		
		tactile.foundation.LayoutManager.updateLayout();
	},	
	backToFashionSpread: function() {
		fashiongrid.hideProductDetail();
		custom.hideFittingRoomPage();
		custom.hideShoppingBasketPage();

		custom.resetFashionSpreadPage();
		
		$('#menu-fashionspread', '#header').siblings().removeClass('selected');
		$('#menu-fashionspread', '#header').addClass('selected');		
		
	},
	viewFashionSpread : function() {

		fashiongrid.hideProductDetail();
		custom.hideFittingRoomPage();
		custom.hideShoppingBasketPage();

		custom.showFashionSpreadPage();
		
		$('#menu-fashionspread', '#header').siblings().removeClass('selected');
		$('#menu-fashionspread', '#header').addClass('selected');
	},
	viewFittingRoom : function() {
		if (!customloader.fittingroomloaded) {
			customloader.fittingroomloader.load({
				url : "/ipad/remote/fittingroom.xml"
			})
		}

		fashiongrid.hideProductDetail();
		custom.hideFashionSpreadPage();
		custom.hideShoppingBasketPage();

		custom.showFittingRoomPage();
		
		$('#menu-fittingroom', '#header').siblings().removeClass('selected');
		$('#menu-fittingroom', '#header').addClass('selected');
	},
	viewShoppingBasket : function() {
		if (!customloader.shoppingbasketloaded) {
			customloader.shoppingbasketloader.load({
				url : "/ipad/remote/shoppingbasket.xml"
			})
		} 

		fashiongrid.hideProductDetail();
		custom.hideFashionSpreadPage();
		custom.hideFittingRoomPage();

		custom.showShoppingBasketPage();
		
		$('#menu-shoppingbasket', '#header').siblings().removeClass('selected');
		$('#menu-shoppingbasket', '#header').addClass('selected');
	},
	slideFashionSpreadView : function(e) {
		var mvfashionspread = page.getComponent("mv-fashionspread");
		var direction = e.direction.toUpperCase();
		if (direction == "LEFT") {
			mvfashionspread.showNext({
				slideto : tactile.Enum.Direction.west,
				slidefrom : tactile.Enum.Direction.east
			});
		} else if (direction == "RIGHT") {
			mvfashionspread.showPrev({
				slideto : tactile.Enum.Direction.east,
				slidefrom : tactile.Enum.Direction.west
			});
		}
	},
	slideFashionSpreadGridView : function(e) {
		var mvfashionspreadgrid = page.getComponent("mv-fashionspreadgrid");
		var direction = e.direction.toUpperCase();
		if (direction == "LEFT") {
			mvfashionspreadgrid.showNext({
				slideto : tactile.Enum.Direction.west,
				slidefrom : tactile.Enum.Direction.east
			});
		} else if (direction == "RIGHT") {
			mvfashionspreadgrid.showPrev({
				slideto : tactile.Enum.Direction.east,
				slidefrom : tactile.Enum.Direction.west
			});
		}
	},
	openFashionGrid : function(e) {
		var mvcontentfashionspread = page.getComponent("mv-content-fashionspread");
		mvcontentfashionspread.showNext({
			slideto : tactile.Enum.Direction.north,
			slidefrom : tactile.Enum.Direction.south
		});

		var mvfashionspread = page.getComponent("mv-fashionspread");
		var mvfashionspreadgrid = page.getComponent("mv-fashionspreadgrid");
		mvfashionspreadgrid.showView(mvfashionspread.selectedIndex);

		custom.toggleFashionSpreadIcon();
	},
	closeFashionGrid : function(e) {
		var mvcontentfashionspread = page.getComponent("mv-content-fashionspread");
		mvcontentfashionspread.showNext({
			slideto : tactile.Enum.Direction.south,
			slidefrom : tactile.Enum.Direction.north
		});

		var mvfashionspread = page.getComponent("mv-fashionspread");
		var mvfashionspreadgrid = page.getComponent("mv-fashionspreadgrid");
		mvfashionspread.showView(mvfashionspreadgrid.selectedIndex);

		custom.toggleFashionSpreadIcon();
	},
	hideFashionSpreadPage : function() {
		var openbutton = page.getComponent("bottom-icon-overlay");
		openbutton.hide();

		var closebutton = page.getComponent("top-icon-overlay");
		closebutton.hide();

		var likethisbutton = page.getComponent("bottom-iconfittingroom-overlay");
		likethisbutton.hide();		
		
		var sidebar = page.getComponent("sidebar-overlay");
		sidebar.hide();

		var vwcontentfashionspread = page.getComponent("vw-content-fashionspread");
		vwcontentfashionspread.hide();
	},
	showFashionSpreadPage : function() {
		var vwcontentfashionspread = page.getComponent("vw-content-fashionspread");
		vwcontentfashionspread.show();

		var mvcontentfashionspread = page.getComponent("mv-content-fashionspread");
		mvcontentfashionspread.showView("content-fashionspread",{
			slideto : tactile.Enum.Direction.south,
			slidefrom : tactile.Enum.Direction.north
		});	
		
		var openbutton = page.getComponent("bottom-icon-overlay");
		openbutton.show();

		var closebutton = page.getComponent("top-icon-overlay");
		closebutton.hide();
		
		var likethisbutton = page.getComponent("bottom-iconfittingroom-overlay");
		likethisbutton.show();
		
		var sidebar = page.getComponent("sidebar-overlay");
		sidebar.show();
	},
	resetFashionSpreadPage: function() {
		var vwcontentfashionspread = page.getComponent("vw-content-fashionspread");
		vwcontentfashionspread.show();

		var mvcontentfashionspread = page.getComponent("mv-content-fashionspread");
		if (mvcontentfashionspread.selectedIndex==0) {
			var openbutton = page.getComponent("bottom-icon-overlay");
			openbutton.show();

			var closebutton = page.getComponent("top-icon-overlay");
			closebutton.hide();
			
			var likethisbutton = page.getComponent("bottom-iconfittingroom-overlay");
			likethisbutton.show();
			
			var sidebar = page.getComponent("sidebar-overlay");
			sidebar.show();					
		}else {
			var openbutton = page.getComponent("bottom-icon-overlay");
			openbutton.hide();

			var closebutton = page.getComponent("top-icon-overlay");
			closebutton.show();
			
			var likethisbutton = page.getComponent("bottom-iconfittingroom-overlay");
			likethisbutton.hide();			

			var sidebar = page.getComponent("sidebar-overlay");
			sidebar.hide();	
		}		
	},
	hideFittingRoomPage : function() {
		var fittingroom = page.getComponent("vw-content-fittingroom");
		if (fittingroom != 'undefined' && fittingroom != null) {
			fittingroom.hide();
		}
	},
	showFittingRoomPage : function() {
		var fittingroom = page.getComponent("vw-content-fittingroom");
		if (fittingroom != 'undefined' && fittingroom != null) {
			fittingroom.show();
			
			var i = $('.item', '#myTopScroll .scroller').length;
			var j = parseFloat($('.item', '#myTopScroll .scroller').css('width')) + parseFloat($('.item', '#myTopScroll .scroller').css('margin-right'));
			var k = parseFloat($('#myTopScroll').css('padding-left'));
			$('#myTopScroll .scroller').css('width', (i*j)+k);
			fitroomTopScroller.refresh();
			
			var o = $('.item', '#myBotScroll .scroller').length;
			var p = parseFloat($('.item', '#myBotScroll .scroller').css('width')) + parseFloat($('.item', '#myBotScroll .scroller').css('margin-right'));
			var q = parseFloat($('#myBotScroll').css('padding-left'));
			$('#myBotScroll .scroller').css('width', (o*p) + q);
			fitroomBotScroller.refresh();
		}
	},
	hideShoppingBasketPage : function() {
		var shoppingbasket = page.getComponent("vw-content-shoppingbasket");
		if (shoppingbasket != 'undefined' && shoppingbasket != null) {
			shoppingbasket.hide();
		}
	},
	showShoppingBasketPage : function() {
		var shoppingbasket = page.getComponent("vw-content-shoppingbasket");
		
		if (shoppingbasket != 'undefined' && shoppingbasket != null) {
			shoppingbasket.show();		
		}
		
		console.log('second load');
		
		if ($('#vw-content-shoppingbasket').length > 0) {
			BasketDB.init();
			scroller.refresh();
		}
	},
	toggleFashionSpreadIcon: function() {
		var openbutton = page.getComponent("bottom-icon-overlay");
		openbutton.toggle();

		var closebutton = page.getComponent("top-icon-overlay");
		closebutton.toggle();
		
		var likethisbutton = page.getComponent("bottom-iconfittingroom-overlay");
		likethisbutton.toggle();			

		var sidebar = page.getComponent("sidebar-overlay");
		sidebar.toggle();		
	},
	toggleFittingRoomMode: function() {
		
		var i=0;
		for(i=0;i<4;i++) {
			
			var item = page.getComponent("fittingitem-content"+i);
			if (item!=null && item!='undefined'){
				item.toggle();
			}
			
			var itemoverlay = page.getComponent("fittingitem-overlay" +i);
			if (itemoverlay !=null && itemoverlay!='undefined') {
				itemoverlay.toggle();
			}
			
		}
	},
	deleteFittingRoomItem: function(index) {
		
		var item = tactile.FlexItem.cast(page.getComponent("fittingroomitem"+ index));
		if (item!='undefined' && item!=null) {
			
			var flexview = tactile.FlexView.cast(page.getComponent("fw-fittingroom-item-list"));
			flexview.remove(item);
			
		}
	}
}

function _editme(e) {
	$(e.currentTarget).parent().append("<div class='right sprite ico check' id='submitme'></div>");
	$('#submitme').click(function(e){
		_submitme(e)
	});
	$(e.currentTarget).parent().append("<div class='right sprite ico back' id='cancelme'></div>");
	$('#cancelme').click(function(e){
		_cancelme(e)
	});
	$(e.currentTarget).remove();
	
	if($('.item', '#myTopScroll').length > 0) {
		$('.close', '#myTopScroll .item').css('display', 'block');
		$('.close', '#myTopScroll .item').click(function(e) {
			$(this).parent().css('display', 'none');
		});
	}
}
function _cancelme(e) {
	$('#myTopScroll .item').each(function(index) {
		var me = $(this);
		if( me.css('display') == 'none' ) me.css('display', 'block');
	});
}
function _submitme(e) {
	$(e.currentTarget).parent().append("<div class='right sprite ico edit' id='editme'></div>");
	$('#editme').click(function(e) {	
		_editme(e);
	});
	
	$('#cancelme').remove();
	$(e.currentTarget).remove();
	
	if($('.item', '#myTopScroll').length > 0) {
		$('.close', '#myTopScroll .item').css('display', 'none');
	}
	
	$('#myTopScroll .item').each(function(index) {
		var me = $(this);
		if( me.css('display') == 'none' ) me.remove();
	});
	
	// REFRESH SCROLL
	var i = $('.item', '#myTopScroll .scroller').length;
	var j = parseFloat($('.item', '#myTopScroll .scroller').css('width')) + parseFloat($('.item', '#myTopScroll .scroller').css('margin-right'));
	$('#myTopScroll .scroller').css('width', (i*j));
	fitroomTopScroller.refresh();
}

page.onready(custom.init);

//tactile.EventManager.addOnloadListener(function() {
//
//	loadingmask.setConfig({
//		loadingmaskId: "loading",
//		progressId:    "loadingmask-progress-info",
//		progressMode:  "progressbar"
//	});
//
//	loadingmask.setState({
//		step:    5,
//		steps:   10,
//		message: "init"
//	});
//	
//});